<template>
  <div>
    <el-dialog v-model="dialogVisible" title="模拟数据" width="800" draggable :fullscreen="false" :show-close="false" @close="close">
      <div class="editor-container"> 
        <el-input v-model="jsonData" type="textarea" :rows="10" placeholder="请输入 JSON 数据" ></el-input>
        <el-button type="primary" @click="printData">确定生成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue';

import { ElMessage } from 'element-plus';
import Mock from 'mockjs';
import JSON5 from 'json5';

import api  from "../api/api.js"
const props = defineProps({
  modelValue: { // 对应父组件 v-model 绑定的值
    type: Boolean,
    default: false
  }
});

// 定义 emit
const emit = defineEmits(['update:modelValue']); // 对应 v-model 的更新事件

// 使用 ref 声明一个本地变量 dialogVisible
const dialogVisible = ref(props.modelValue);

// 监听父组件传递的 modelValue 的变化
watch(() => props.modelValue, (newValue) => {
  dialogVisible.value = newValue;
   
});

 
 
const jsonData = ref(`{
  '/api': {
    code: 200,
    msg: 'success',
    data: {
      'id|+1': 1,
      name: '@cname',
      title: '@csentence(5, 10)',
      date: '@date(yyyy-MM-dd)',
      person: '@name',
      location: '@province',
      company: '@company',
      timestamp: '@now',
      amount: '@float(100, 10000, 2, 2)',
      email: '@email',
      quantity: '@integer(1, 100)',
      status: '@pick(["active", "inactive", "pending", "completed"])'
    },
    'list|5-10': [
      {
        'id|+1': 1,
        name: '@cname',
        title: '@csentence(5, 10)',
        date: '@date(yyyy-MM-dd)',
        person: '@name',
        location: '@province',
        company: '@company',
        timestamp: '@now',
        amount: '@float(100, 10000, 2, 2)',
        email: '@email',
        quantity: '@integer(1, 100)',
        status: '@pick(["active", "inactive", "pending", "completed"])'
      }
    ]
  }
}`);

const close = ()=>{
    emit('update:modelValue', false); // 通知父组件更新绑定值
}
const printData = async () => {
  console.log('输入的数据:', jsonData.value);
  close()
  const data = Mock.mock(JSON5.parse(jsonData.value));
  console.log('打印的数据:', data);
  ElMessage.success('数据已打印到控制台');
  const res = await api.setmock({ data: data }) 
  console.log('响应:', res);
  
};
 
</script>

<style scoped>
.editor-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.el-input {
  flex: 1;
}

.el-button {
  align-self: flex-end;
}
</style>